package com.it.crud.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.it.crud.domain.User;
import com.it.crud.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    // 创建用户
    @PostMapping
    public boolean createUser(@RequestBody User user) {
        return userService.save(user);
    }
    
    // 根据ID查询用户
    @GetMapping("/{id}")
    public User getUserById(@PathVariable Long id) {
        return userService.getById(id);
    }
    
    // 查询所有用户
    @GetMapping
    public List<User> getAllUsers() {
        return userService.list();
    }
    
    // 分页查询用户
    @GetMapping("/page")
    public IPage<User> getUsersByPage(@RequestParam(defaultValue = "1") Integer pageNum,
                                      @RequestParam(defaultValue = "10") Integer pageSize) {
        Page<User> page = new Page<>(pageNum, pageSize);
        return userService.page(page);
    }
    
    // 根据条件查询用户
    @GetMapping("/select")
    public List<User> selectUsers(@RequestParam String name) {
            return userService.list(new LambdaQueryWrapper<User>().like(User::getName, name));

    }
    
    // 更新用户
    @PutMapping
    public boolean updateUser(@RequestBody User user) {
        return userService.updateById(user);
    }
    
    // 根据ID删除用户
    @DeleteMapping("/{id}")
    public boolean deleteUser(@PathVariable Long id) {
        return userService.removeById(id);
    }

}    